/*--------------------------+
|	   EmitterManager		|
|	---------------------	|
|	Contains, updates and	|
|	renders emitters, also	|
|	managing their memory	|
+--------------------------*/

#include "EmitterManager.h"
#include "Emitter.h"

EmitterManager::EmitterManager(void)
{
}


EmitterManager::~EmitterManager(void)
{
}

// Get the singleton
EmitterManager* EmitterManager::GetInstance(void)
{
	static EmitterManager instance;
	return &instance;
}

// Create a template emitter
int EmitterManager::CreateEmitterTemplate(Emitter* emitter)
{
	MasterEmitters.push_back(emitter);
	return MasterEmitters.size() - 1;
}

// Clone a template
Emitter* EmitterManager::CreateEmitterFromTemplate(int id)
{
	Emitter* e = new Emitter(*MasterEmitters[id]);
	return e;
}

// Render all the emitters
void EmitterManager::Render(void) const
{
	for(unsigned int i = 0; i < Emitters.size(); ++i)
		Emitters[i]->Render();

	for(unsigned int i = 0; i < Bursts.size(); ++i)
		Bursts[i]->Render();
}

// Update all the emitters
void EmitterManager::Update(float elapsedTime)
{
	for(unsigned int i = 0; i < Emitters.size(); ++i)
		Emitters[i]->Update(elapsedTime);

	Emitters.shrink_to_fit();

	for(unsigned int i = 0; i < Bursts.size(); ++i)
		Bursts[i]->Update(elapsedTime);

	Bursts.shrink_to_fit();
}

// Close the system down
void EmitterManager::Shutdown(void)
{
	// Clean up the active emitters
	for(unsigned int i = 0; i < Emitters.size(); ++i)
	{
		Emitters[i]->Shutdown();
		delete Emitters[i];
		Emitters.erase(Emitters.begin() + i);
	}

	// Destroy the templates
	for(unsigned int i = 0; i < MasterEmitters.size(); ++i)
	{
		MasterEmitters[i]->Shutdown();
		delete MasterEmitters[i];
		MasterEmitters.erase(MasterEmitters.begin() + i);
	}

	// Destroy bursts
	for(unsigned int i = 0; i < Bursts.size(); ++i)
	{
		Bursts[i]->Shutdown();
		delete Bursts[i];
		Bursts.erase(Bursts.begin() + i);
	}
}

// Fire a single burst with an emitter then destroy it
void EmitterManager::FireBurstEmitter(Emitter* emitter)
{
	Bursts.push_back(emitter);
	emitter->Burst();
}

// Destroy a specific template emitter
void EmitterManager::DestroyTemplate(unsigned int index)
{
	delete MasterEmitters[index];
	MasterEmitters.erase(MasterEmitters.begin() + index);
}